<template>
    <div>
        <a-row :gutter="20"><a-col :span="14">
                <a-row>
                    <!-- <a-input style="width: 25%"  placeholder="请输常规仪器串名称" v-model:value="a"></a-input> -->
                    <a-button type="dashed" style="width: 33.33%;" @click="addInstrument">
                        <template #icon><node-index-outlined /></template>添加仪器
                    </a-button>
                    <a-button type="dashed" style="width: 33.33%;" @click="resetInstrument">
                        <template #icon><node-index-outlined /></template>重置
                    </a-button>
                    <a-button type="dashed" style="width: 33.33%;" @click="saveInstrument">
                        <template #icon><node-index-outlined /></template>保存
                    </a-button>
                </a-row>
                <a-table :pagination="false" :showHeader="false" :columns="instrumentListColumns"
                    :data-source="instrumentList">
                    <template #bodyCell="{ column, text, record }"><template v-if="column.dataIndex === 'operation'">
                            <a-popconfirm title="请选择在下方或在上方插入" ok-text="向下" cancel-text="向上"
                                @confirm="insertToDown(record.instrumentId)" @cancel="insertToUp(record.instrumentId)">
                                <a-button style="margin-left:30px">插入 </a-button>
                            </a-popconfirm>
                            <a-button style="margin-left:10px" @click="delInstrument(record.instrumentId)"> 删除 </a-button>
                        </template></template> </a-table>
            </a-col>
            <a-col :span="10">
                <div ref="d3CanvasRef">
                    <canvasIns :data="instrumentList"></canvasIns>
                </div>
            </a-col></a-row>
        <!-- 选择仪器弹窗 -->
        <AntdConfirmModal @confirm="submitUpdateForm" :title=modalTitle ref="instrumentModalRef" width="1200px">
            <a-row style="margin-bottom:10px">
                <a-select ref="select" v-model:value="optionType" style="width: 120px">
                    <a-select-option value="instrument">仪器信息</a-select-option>
                    <a-select-option value="horsehead">马笼头</a-select-option>
                </a-select></a-row>
            <horsehead-popup v-if="optionType === 'horsehead'" @horseheadSelection="horseheadSelection"></horsehead-popup>
            <instrument-popup v-if="optionType === 'instrument'"
                @instrumentSelection="instrumentSelection"></instrument-popup>
        </AntdConfirmModal>
        <!-- 保存仪器弹窗 -->
        <AntdConfirmModal @confirm="submitSaveForm" title=保存新建仪器串 width="600px" ref="saveCombinationModalRef">
            <a-form :label-col="{ span: 5 }" :wrapper-col="{ span: 16 }">
                <a-form-item label="仪器串名称" name="combinationName">
                    <a-input v-model:value="formState.combinationName" />
                </a-form-item>
                <a-form-item label="仪器串类型" name="combinationSeries">
                    <a-input v-model:value="formState.combinationSeries" />
                </a-form-item>
            </a-form>
        </AntdConfirmModal>
    </div>
</template>
<script setup>
import useApp from '@/hooks'
import canvasIns from '@/custom/preTest/pages/plan/components/instrument/canvas'
import InstrumentPopup from '@/custom/preTest/pages/plan/components/instrument/type/InstrumentPopup.vue'
import HorseheadPopup from "@/custom/preTest/pages/plan/components/instrument/type/HorseheadPopup.vue";
import { createOne, updateOne, queryOne, getOne, } from "@/api/tool/combination.js";
import html2canvas from "html2canvas";
const props = defineProps({
    combinationData: {
        type: Object,
    },
    state: {
        type: String,
    }
});
const { $, proxy } = useApp()
const instrumentId = ref(null)
const modalTitle = ref(null)
const instrumentModalRef = ref(null)
const saveCombinationModalRef = ref(null)
const d3CanvasRef = ref(null);
const instrumentList = ref([])
const instrumentSelectionData = ref([])
const horseheadSelectionData = ref([])
const optionType = ref("instrument")
const formState = ref({
    combinationName: "",
    combinationSeries: "CPlog",
    instrumentIdList: [],
})
const instrumentListColumns = ref([
    {
        dataIndex: 'instrumentId',
        width: 100,
    }, {
        dataIndex: 'instrumentName',
    }, {
        dataIndex: 'operation',
        fixed: 'right',
        width: 230,
    }
])
const addInstrument = () => {
    modalTitle.value = '选择添加的仪器'
    instrumentModalRef.value.openModal()
}
const resetInstrument = () => {
    instrumentList.value = []
}
const saveInstrument = () => {
    saveCombinationModalRef.value.openModal()
}
const insertToDown = (id) => {
    modalTitle.value = '选择向下插入的仪器'
    instrumentId.value = id
    instrumentModalRef.value.openModal()
}
const insertToUp = (id) => {
    modalTitle.value = '选择向上插入的仪器'
    instrumentId.value = id
    instrumentModalRef.value.openModal()

}
//仪器弹窗
function instrumentSelection(e) {
    instrumentSelectionData.value = e
}
//马笼头弹窗
function horseheadSelection(e) {
    horseheadSelectionData.value = e
}
// 选择仪器/马笼头
function submitUpdateForm() {
    horseheadSelectionData.value.forEach(e => {
        e.instrumentId = e.horseheadId
        e.instrumentName = e.horseheadName
    })
    let array = [...horseheadSelectionData.value, ...instrumentSelectionData.value]
    console.log('array', array);
    if (modalTitle.value === '选择添加的仪器') {
        instrumentList.value = [...instrumentList.value, ...array]
    }
    else {
        let index = instrumentList.value.findIndex(item => item.instrumentId == instrumentId.value)
        const position = modalTitle.value === '选择向上插入的仪器' ? 0 : 1
        instrumentList.value.splice(index + position, 0, ...array);
        instrumentList.value = [...instrumentList.value]
        instrumentId.value = null
    }
    console.log('instrumentList.value', instrumentList.value);
    horseheadSelectionData.value = []
    instrumentSelectionData.value = []
    instrumentModalRef.value.closeModal()
}
function delInstrument(id) {
    instrumentList.value = instrumentList.value.filter(item => item.instrumentId !== id);
}
// 提交完成
function submitSaveForm() {
    // console.log('instrumentList.value', instrumentList.value);
    instrumentList.value.forEach(res => {
        formState.value.instrumentIdList.push(res.id)
    })
    setTimeout(() => {
        html2canvas(d3CanvasRef.value).then((canvas) => {
            const imageData = canvas.toDataURL("image/png");
            formState.value.file = imageData;
            console.log('formState.value', formState.value);
            if (props.state == '新增') {
                createOne(formState.value).then(res => {
                    saveCombinationModalRef.value.closeModal()
                    $.showToast({
                        title: '新增成功',
                        icon: 'success'
                    })
                    instrumentList.value = []
                    formState.value = {}
                })
            } else if (props.state == '修改') {
                updateOne(formState.value).then(res => {
                    saveCombinationModalRef.value.closeModal()
                    $.showToast({
                        title: '修改成功',
                        icon: 'success'
                    })
                    instrumentList.value = []
                    formState.value = {}
                })
            }
        });
    }, 1000);
}

//获取已选择的仪器串数据
function getCombList() {
    console.log('state', props.state);
    formState.value.instrumentIdList = []
    if (props.state == '修改') {
        // console.log('编辑', props.combinationData);
        formState.value.combinationName = props.combinationData.combinationName
        formState.value.id = props.combinationData.id
        getOne(props.combinationData.id).then((res) => {
            // 查找是否含有马笼头
            res.forEach((e) => {
                // 如果有，将马笼头仪器参数名称与其他仪器参数名称统一
                if (e.hasOwnProperty("horseheadId")) {
                    e.instrumentId = e.horseheadId;
                    e.instrumentName = e.horseheadName;
                }
            });
            instrumentList.value = res;
        });
    }
}
getCombList();
</script>